import re
import tkinter as tk

import pygetwindow as gw
import win32gui as wg

def get_all_titles() -> list[str]:
    """获取所有已打开窗口标题"""
    tmp: list[str] = gw.getAllTitles()
    ret: list[str] = []
    for i in tmp:
        if len(i) == 0:
            continue
        ret.append(i)
    return ret

def find_window_by_title_win32gui(title: str) -> int:
    """返回窗口句柄，如果不存在则返回0"""
    hwnd = wg.FindWindow(None, title)
    return hwnd

def find_window_by_title_pygetwindow(title: str) -> int:
    """返回窗口句柄，如果不存在则返回0"""
    pid_info = gw.getWindowsWithTitle(title)
    pid = re.findall('hWnd=(\d+)', str(pid_info))
    if len(pid) == 0:
        pid = 0
    else:
        pid = int(pid[0])
    return pid

def set_parent(cid: int, pid: int):
    wg.SetParent(cid, pid)

def get_tkinter_hwnd(root: tk.Tk | tk.Toplevel) -> int:
    return int(root.wm_frame(), 16)

def set_parent_tkinter(child: tk.Tk | tk.Toplevel, parent: tk.Tk | tk.Toplevel):
    """设置嵌套窗口，虽然可以将子窗口作为父窗口，但生命周期还是统一为初始窗口管理"""
    parent.update()
    cid = get_tkinter_hwnd(child)
    pid = get_tkinter_hwnd(parent)
    set_parent(cid, pid)

def get_tkinter_child_window(root: tk.Tk):
    children = root.winfo_children()
    ret: dict[str, tk.Toplevel] = {}
    for i in children:
        if isinstance(i, tk.Toplevel):
            ret.setdefault(str(i.title()), i)
    return ret